package me.huha.client;

import java.io.File;
import java.util.List;
import java.util.Map;

import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;

import me.huha.commons.ToCcBccAddressDTO;
import me.huha.commons.email.PropertiesDTO;
import me.huha.commons.email.UserEmailDTO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Title: EmailBase.java
 * @Author: Yepx
 * @mail: yepx2013@gmail.com
 * @CreateTime: 2017年6月16日 下午1:54:05
 * @Todo: javax.mail 封装
 */
public abstract class EmailBase {
	
	private Logger logger = LoggerFactory.getLogger(EmailBase.class);
	
	protected PropertiesDTO propertiesDto;
	
	protected Session session = null;
	protected Folder folder = null;
	protected Store store = null;
	
	protected Transport transport = null;
	
	protected UserEmailDTO emailDto;
	
	public EmailBase(PropertiesDTO propertiesDto, UserEmailDTO emailDto) {
		super();
		this.propertiesDto = propertiesDto;
		this.emailDto = emailDto;
	}
	
	/**
	 * 获取邮件提供商 smtp 协议 服务连接
	 * @param user
	 * @param pass
	 */
	public Boolean sendConnect() throws MessagingException {
		
		Boolean result = false;
		
		// 取得一个Store对象
		session = Session.getInstance(propertiesDto.getProps(), new EmailAuthenticator(emailDto.getEmail(), emailDto.getPassWord()));
		session.setDebug(false);
		transport = session.getTransport(this.propertiesDto.getSendEnum().getDesc());
		transport.connect(this.emailDto.getEmail(), this.emailDto.getPassWord());
		
		result = true;

		return result;
	}
	
	/**
	 * 关闭连接
	 */
	public void closeConnect() {
		try {
			if (folder != null)
				folder.close(true); // 关闭连接时是否删除邮件，true删除邮件
			if (transport != null) {
				transport.close();
			}
		} catch (MessagingException e) {
			e.printStackTrace();
		} finally {
			try {
				if (store != null)
					store.close();// 关闭收件箱连接
				    session = null;
			} catch (MessagingException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 发送邮件
	 * @param uuid
	 * @param toCcBccAddress
	 * @param messageTitle
	 * @param messageContent
	 * @param imgList
	 * @param fileList
	 * @return
	 */
	public abstract Boolean sendEmail(String uuid, ToCcBccAddressDTO toCcBccAddress, String messageTitle, String messageContent, List<File> imgList, List<File> fileList, Map<String, String> extendMap);
	
}
